package com.tsingteng.cosfun.callback;

import android.content.Context;


import com.google.gson.JsonParseException;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.bean.BaseDataBean;
import com.tsingteng.cosfun.mvp.presenter.BasePresenter;
import com.tsingteng.cosfun.mvp.view.IView;
import com.tsingteng.cosfun.utils.ToastUtils;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.observers.DisposableObserver;


/**
 * 描述: 通用observer回调
 * 创建人: 肖利
 *时间: 2018/7/30
 * qq: (872179966)
 */

public abstract class BaseRxObserver<T> extends DisposableObserver<BaseDataBean<T>> {
    private IView mView;

    public BaseRxObserver(BasePresenter basePresenter) {
        this.mView = basePresenter.getView();
    }


    @Override
    protected void onStart() {
        super.onStart();
//        mView.showLoading("正在加载中...");
    }

    @Override
    public void onError(Throwable e) {
        mView.hideLoading();
        /**
         * 处理异常
         */
        dealWithExposition(AppContext.getContext(),e);
        mView.showError();
    }

    /**
     * 处理异常
     * @param context
     * @param t
     */
    private void dealWithExposition(Context context, Throwable t) {
        if (t instanceof ConnectException || t instanceof UnknownHostException) {
            //连接错误
            ToastUtils.showToast("请检查您的网络");
        } else if (t instanceof InterruptedException) {
            //连接超时
            ToastUtils.showToast("连接超时");
        } else if (t instanceof JsonParseException
                || t instanceof JSONException
                || t instanceof ParseException) {
            //解析错误
            ToastUtils.showToast("解析错误");
        } else if (t instanceof SocketTimeoutException) {
            //请求超时fa
            ToastUtils.showToast("请求超时");
        } else if (t instanceof retrofit2.adapter.rxjava2.HttpException ){
            //未知错误
            ToastUtils.showToast("请检查您的网络！");
        } else  {
            //未知错误
            ToastUtils.showToast("未知错误");
        }
    }

    @Override
    public void onComplete() {
        mView.hideLoading();
    }
}
